<?php
/**
 * Created by PhpStorm.
 * User: 24369
 * Date: 2021/6/24
 * Time: 15:05
 */
namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\validate\LoginValidate;
use mailer\tp6\Mailer;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Session;

class Login extends BaseController
{
    public function initialize()
    {
    }
    public function login()
    {
        $change=Request::param('change','');
        //判断是否有cookie如果有cookie变查询数据与cookie对比
        if (cookie('free')&&!$change){
            //把cookie变为数组
            $token=explode('-',cookie('free'));
            //通过cookie数组中的id进行数据查询
            $user=\app\admin\model\Admin::field(true)->find($token[0]);
            //查询后账号密码进行加密与cookie中的加密进行对比
            $tokens=md5(md5($user['name']).md5($user['pwd']).'token');
            if ($token[1]==$tokens){
                return  view('login/free',$user->toArray());
            }
        }
        if (Request::isPost()){
            $post=Request::post();
            //缓存中的登录失败时间
            $time=\cache($post['name'].'_time');
            //如果当天错误次数大于等于5，禁止当天登录
            if (\cache($post['name'])>=5&&time()-$time<=86400){
                $this->error('禁止当天登录');
            }else if (\cache($post['name'])>=5&&time()-$time>=86400){
                Cache::delete($post['name']);
                Cache::delete($post['name'].'_time');
            }
            //验证器场景验证，如果该账号在一小时内登录失败3次，便会开启验证码验证
            if (\cache($post['name'])>=3 && time()-$time<=3600){
                $scene='isCode';
            }else{
                $scene='noCode';
            }
            try{
                validate(LoginValidate::class)->scene($scene)->check($post);
            }catch (ValidateException $validateException){
                $msg=$validateException->getMessage();
            }
            if (isset($msg))        $this->error($msg);
            //通过用户输入的账号密码进行查询
            $user=\app\admin\model\Admin::where('name','=',$post['name'])
                ->where('pwd','=',md5($post['password']))
                ->find();
            if ($user){
                //添加会话
                session('userInfo',$user);
                //删除缓存账号次数
                Cache::delete($post['name']);
                //删除缓存账号登录失败时间
                Cache::delete($post['name'].'_time');
                //判断有无cookie，进行添加
                if (isset($post['free'])&&$post['free']==1){
                    $token=md5(md5($user['name']).md5($user['pwd']).'token');
                    cookie('free',$user['id'].'-'.$token,86400*30);
                }
                $this->success('登陆成功',url('Index/index'));
            }else{
                //缓存账号失败次数
                Cache::inc($post['name']);
                //缓存账号第一次登录失败时间
                if (!cache($post['name'].'_time')){
                    \cache($post['name'].'_time',time());
                }
                $this->error('用户名或密码错误',url('Login/login',['names'=>$post['name'],'change'=>1]));
            }
        }else{
            return  view();
        }
    }
    //退出登录
    public function loginOut()
    {
        Session::clear();
        $this->success('退出成功',url('Login/login'));
    }
    //ajax验证是否需要开启验证码
    public function ajaxName()
    {
        $name=Request::post('name');
        $time=\cache($name.'_time');
        //账号当前时间减去缓存时间大于一天则删除缓存
        if (\cache($name)>=5&&time()-$time>=86400){
            Cache::delete($name);
            Cache::delete($name.'_time');
        }
        //账号一小时内错误三次开启验证码
        if (\cache($name)>=3 && time()-$time<=3600){
            return  json(['name'=>1,'msg'=>'需要开启验证码']);
        }else{
            return  json(['name'=>0,'msg'=>'不需要开启验证码']);
        }
    }
    //免登陆
    public function loginFree()
    {
        //判断有无cookie
        if (\cookie('free')){
            //把加密后的cookie变为数组
            $token=explode('-',\cookie('free'));
            //通过cookie中的id查询
            $user=\app\admin\model\Admin::field(true)->find($token[0]);
            //将查询出来的账号密码进行加密
            $tokens=md5(md5($user['name']).md5($user['pwd']).'token');
            //cookie中的加密和查询数据的加密作对比
            if ($token[1] == $tokens){
                \session('userInfo',$user);
                $this->success('登陆成功',url('Index/index'));
            }else{
                $this->error('账号或密码错误','',[],99999);
            }
        }
    }
    //用户邮箱修改密码
    public function pass()
    {
        if (Request::isPost()){
            $post=Request::post();
            $post['pwd']=md5($post['pwd']);
            $res=\app\admin\model\Admin::update($post);
            if ($res){
                $this->success('ok',url('Login/login'));
            }else{
                $this->error('no');
            }
        }
        $token=Request::param('token');
        $user=\app\admin\model\Admin::find($token);
        return view('',$user->toArray());
    }
    //忘记密码
    public function sendEmail()
    {
        if (Request::isPost()){
            $email=Request::post('email');
            //通过用户发送的邮箱进行查询
            $user=\app\admin\model\Admin::where('email','=',$email)->find();
            if ($user){
                //修改密码网页路径
                $url='http://hf26.top/index.php/admin/Login/pass?token='.$user['id'];
                //发送邮件
                $mailer=Mailer::instance();
                $mailer->from('2436934253@qq.com', 'xdz')
                    ->to($email)
                    ->subject('找回密码')
                    ->text($url)
                    ->send();
            }else{
                $this->error('邮箱error');
            }
        }
        return  view();
    }
    //ajax验证码验证
    public function ajaxCode()
    {
        $code=Request::post('code');
        if (captcha_check($code,false)){
            return  json(['code'=>1,'msg'=>'成功']);
        }else{
            return  json(['code'=>0,'msg'=>'失败']);
        }
    }
}